﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Xml.Linq;

namespace Twi.COMMON.Core
{

    public class TwiXmlHelper
    {
        //序列化及范序列化，请参考http://blog.okbase.net/haobao/archive/62.html 

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string xml)
        {
            using (StringReader sr = new StringReader(xml))
            {
                XmlSerializer xmldes = new XmlSerializer(type);
                return xmldes.Deserialize(sr);
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static object Deserialize(Type type, Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(type);
            return xmldes.Deserialize(stream);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <example>
        ///  public class Student
        ///  {
        ///      public string Name { set; get; }
        ///      public int Age { set; get; }
        ///  } 
        ///  Student stu1 = new Student() { Name = "okbase", Age = 10 };
        ///  string xml = XmlUtil.Serializer(typeof(Student), stu1);
        ///  Console.Write(xml);
        /// </example>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }

        /// <summary>
        /// 获取xml文件的根节点
        /// </summary>
        /// <param name="xmlFileFullPath"></param>
        /// <returns></returns>
        public static XmlElement GetRootElement(string xmlFileFullPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlFileFullPath);
            XmlElement root = xmlDoc.DocumentElement;
            return root;            
        }


        /// <summary>
        /// 将IList对象转换为
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="nodeName"></param>
        /// <param name="rootNameSuffix"></param>
        /// <returns></returns>
        public static XElement ConvertIListToXElement<T>(IList<T> list, string nodeName="Item", string rootNameSuffix = "List") 
        {
            if (list == null || list.Count == 0)
            {
                return null;
            }

            XElement element = new XElement(nodeName + rootNameSuffix);
            nodeName = string.IsNullOrEmpty(nodeName) ? typeof(T).Name : nodeName;

            foreach (T entity in list)
            {
                XElement elchild = ConvertToXElement<T>(entity, nodeName);
                if (elchild != null)
                {
                    element.Add(elchild);
                }
            }

            return element;

        }

        /// <summary>
        /// 将单个对象或值转换为XElement对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="nodeName">节点名称</param>
        /// <returns></returns>
        public static XElement ConvertToXElement<T>(T t,string nodeName="Item") 
        {
            nodeName = string.IsNullOrEmpty(nodeName) ? typeof(T).Name : nodeName;
            XElement element = new XElement(nodeName);
            if (t == null)
            {
                return null;
            }
            else if (typeof(T) == typeof(string) || typeof(T).IsValueType)
            {
                element.SetValue(t);
            }
            else
            {           
                PropertyInfo[] properties = typeof(T).GetProperties();
                XElement innerElement = null;
                object propertyValue = null;
                foreach (PropertyInfo property in properties)
                {
                    propertyValue = property.GetValue(t, null);
                    innerElement = new XElement(property.Name, propertyValue);
                    element.Add(innerElement);
                }
            }
            return element;
        }

        /// <summary>
        /// List<XElement> 克隆
        /// </summary>
        /// <param name="xeList"></param>
        /// <returns></returns>
        public static List<XElement> XElementClone(IList<XElement> xeList)
        {
            if (xeList == null) return null;

            List<XElement> newXelist = new List<XElement>();
            for (var i = 0; i < xeList.Count; i++)
            {
                newXelist.Add(XElementClone(xeList[i]));
            }
            return newXelist;
        }

        /// <summary>
        /// XElement克隆
        /// </summary>
        /// <param name="xe"></param>
        /// <returns></returns>
        public static XElement XElementClone(XElement xe)
        {
            return  new XElement(xe.Name, xe.Elements());
        }
    }
}







 

